package com.example.zookeeper.schedule;

import com.alibaba.fastjson.JSON;

import com.example.zookeeper.controller.ZookeeperController;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/9/2 13:20
 */
@Component
public class TimerTask {
    private static final Logger log = LoggerFactory.getLogger(TimerTask.class);

    @Autowired
    private CuratorFramework curatorFramework;

    @Value("${server.port}")
    private String port;

    /**
     * 使用zookeeper实现集群只一个应用实例执行定时任务
     */
    @Scheduled(cron = "0/5 * * * * *")
    public void task() {
        try (LeaderLatch leaderLatch = new LeaderLatch(curatorFramework, "/timerTask");) {
            leaderLatch.start();
            // Leader选举需要一些时间，等待2秒
            Thread.sleep(2000);
            // 判断是否为主节点

            if (leaderLatch.hasLeadership()) {
                log.info("    port:{}是领导", port);
                // 定时任务的业务逻辑代码
            } else {
                log.info("    port:{}是从属", port);
            }
            log.info("  leaderLatch:{}", JSON.toJSONString(leaderLatch));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
